import router from './router'
import store from './store'
import { Message } from 'element-ui'
// progress bar 进度条引入
import NProgress from 'nprogress'
// progress bar style  进度条样式引入
import 'nprogress/nprogress.css'
// get token from cookie  获取token方法引入
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
// NProgress Configuration 进度条配置
NProgress.configure({ showSpinner: false })
// no redirect whitelist 路由白名单
const whiteList = ['/login', '/updatePassword']

router.beforeEach(async(to, from, next) => {
  // start progress bar  进度条开始
  NProgress.start()

  // set page title  动态设置标签名字
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in  获取token验证登录权限
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page  已经登录登录的话重定向到首页
      next({ path: '/' })
      // 进度条结束
      NProgress.done()
    } else {
      // 获取用户名
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          // await store.dispatch('user/getInfo')
          // 放行
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    // 没有token  验证是否在白名单内
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      // 在白名单内可跳转
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // 没有权限就重定向到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  // 路由跳转结束，关闭进度条
  NProgress.done()
})
